{% extends "layout.html" %}

{% block title %}网盘搜索{% endblock %}

{% block css %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/pansou.css') }}">
{% endblock %}

{% block page_title %}网盘搜索{% endblock %}

{% block content %}
<div class="pansou-container" id="pansou-container">
    <div class="pansou-header">
        <div class="pansou-logo">
            <i class="fas fa-cloud logo-icon"></i>
            <h1>网盘搜索</h1>
        </div>
    </div>

    <div class="search-box">
        <input type="text" id="search-input" placeholder="搜索网盘资源...">
        <button id="search-button">
            <i class="fas fa-search"></i>
        </button>
    </div>
    
    <div class="hot-keywords" id="hot-keywords">
        <div class="hot-keywords-title">热门搜索：</div>
        <div class="hot-keywords-list" id="hot-keywords-list">
            <!-- 热搜关键词将在这里动态加载 -->
            <div class="hot-keyword-loading">加载中...</div>
        </div>
    </div>
    
    <!-- 筛选选项，初始隐藏 -->
    <div class="filter-options" id="filter-options" style="display: none;">
        <div class="filter-group">
            <span class="filter-label">时间：</span>
            <div class="filter-items">
                <div class="filter-item active" data-time="">全部</div>
                <div class="filter-item" data-time="week">一周内</div>
                <div class="filter-item" data-time="month">一个月内</div>
                <div class="filter-item" data-time="three_month">三个月内</div>
                <div class="filter-item" data-time="year">一年内</div>
            </div>
        </div>
        
        <div class="filter-group">
            <span class="filter-label">类型：</span>
            <div class="filter-items">
                <div class="filter-item active" data-type="">全部</div>
                <div class="filter-item" data-type="BDY">百度网盘</div>
                <div class="filter-item" data-type="ALY">阿里云盘</div>
                <div class="filter-item" data-type="QUARK">夸克网盘</div>
                <div class="filter-item" data-type="XUNLEI">迅雷云盘</div>
            </div>
        </div>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-container" id="loading-container" style="display: none;">
        <div class="loading-spinner"></div>
        <p>正在搜索...</p>
    </div>
    
    <!-- 错误信息 -->
    <div class="error-message" id="error-message" style="display: none;"></div>
    
    <!-- 搜索结果列表 -->
    <div class="search-results" id="search-results" style="display: none;">
        <!-- 搜索结果将动态加载到这里 -->
    </div>
    
    <!-- 分页控件 -->
    <div class="pagination" id="pagination" style="display: none;">
        <!-- 分页按钮将动态加载到这里 -->
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const pansouContainer = document.getElementById('pansou-container');
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        const hotKeywordsList = document.getElementById('hot-keywords-list');
        const filterOptions = document.getElementById('filter-options');
        const loadingContainer = document.getElementById('loading-container');
        const errorMessage = document.getElementById('error-message');
        const searchResults = document.getElementById('search-results');
        const pagination = document.getElementById('pagination');
        
        // 搜索状态变量
        let currentQuery = '';
        let currentPage = 1;
        let currentTime = '';
        let currentType = '';
        const pageSize = 10;
        let totalPages = 0;
        
        // 初始化加载热搜关键词
        loadHotKeywords();
        
        // 加载热搜关键词
        function loadHotKeywords() {
            fetch('/pansou/hot_keywords')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取热搜关键词失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data && data.data && data.data.length > 0) {
                        renderHotKeywords(data.data);
                    } else {
                        hotKeywordsList.innerHTML = '<div class="no-keywords">暂无热搜关键词</div>';
                    }
                })
                .catch(error => {
                    hotKeywordsList.innerHTML = `<div class="error-keywords">${error.message}</div>`;
                });
        }
        
        // 渲染热搜关键词
        function renderHotKeywords(keywords) {
            hotKeywordsList.innerHTML = '';
            keywords.forEach(keyword => {
                const keywordElement = document.createElement('div');
                keywordElement.className = 'hot-keyword';
                keywordElement.textContent = keyword.name;
                keywordElement.addEventListener('click', () => {
                    searchInput.value = keyword.name;
                    performSearch();
                });
                hotKeywordsList.appendChild(keywordElement);
            });
        }
        
        // 搜索按钮点击事件
        searchButton.addEventListener('click', performSearch);
        
        // 搜索输入框回车事件
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
        
        // 筛选选项点击事件
        document.querySelectorAll('.filter-item').forEach(item => {
            item.addEventListener('click', function() {
                // 更新同组中的激活状态
                const filterGroup = this.closest('.filter-group');
                filterGroup.querySelectorAll('.filter-item').forEach(i => {
                    i.classList.remove('active');
                });
                this.classList.add('active');
                
                // 更新筛选值
                if (filterGroup.querySelector('.filter-label').textContent.includes('时间')) {
                    currentTime = this.getAttribute('data-time');
                } else {
                    currentType = this.getAttribute('data-type');
                }
                
                // 重新搜索
                currentPage = 1;
                if (currentQuery) {
                    searchWithFilters();
                }
            });
        });
        
        // 执行搜索
        function performSearch() {
            const query = searchInput.value.trim();
            if (!query) {
                showError('请输入搜索关键词');
                return;
            }
            
            // 更新当前查询
            currentQuery = query;
            currentPage = 1;
            
            // 显示筛选选项
            filterOptions.style.display = 'block';
            
            // 滚动到顶部并转换为结果页模式
            window.scrollTo(0, 0);
            pansouContainer.classList.add('results-mode');
            
            // 执行带筛选条件的搜索
            searchWithFilters();
        }
        
        // 带筛选条件的搜索
        function searchWithFilters() {
            // 显示加载状态
            showLoading();
            
            // 准备搜索参数
            const searchParams = {
                q: currentQuery,
                page: currentPage,
                size: pageSize,
                time: currentTime,
                type: currentType,
                exact: true
            };
            
            // 发送搜索请求
            fetch('/pansou/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(searchParams)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.error || '搜索失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                hideLoading();
                
                if (data && data.code === 200 && data.data) {
                    renderSearchResults(data.data);
                } else {
                    throw new Error(data.msg || '搜索失败');
                }
            })
            .catch(error => {
                hideLoading();
                showError(error.message);
            });
        }
        
        // 渲染搜索结果
        function renderSearchResults(data) {
            // 隐藏错误信息
            errorMessage.style.display = 'none';
            
            // 显示结果容器
            searchResults.style.display = 'block';
            
            // 清空搜索结果
            searchResults.innerHTML = '';
            
            // 检查是否有结果
            const results = data.list || [];
            const total = data.total || 0;
            
            if (results.length === 0) {
                searchResults.innerHTML = '<div class="no-results">没有找到相关网盘资源</div>';
                pagination.style.display = 'none';
                return;
            }
            
            // 显示结果信息
            const resultsInfo = document.createElement('div');
            resultsInfo.className = 'results-info';
            resultsInfo.textContent = `共找到 ${total} 个相关资源`;
            searchResults.appendChild(resultsInfo);
            
            // 渲染每个结果项
            results.forEach(result => {
                const resultItem = document.createElement('div');
                resultItem.className = 'result-item';
                
                // 创建结果标题行
                const titleRow = document.createElement('div');
                titleRow.className = 'result-title-row';
                
                // 标题
                const title = document.createElement('div');
                title.className = 'result-title';
                title.textContent = result.disk_name;
                titleRow.appendChild(title);
                
                // 资源类型
                const type = document.createElement('div');
                type.className = 'result-type';
                type.textContent = result.disk_type || '未知';
                titleRow.appendChild(type);
                
                // 分享人
                const user = document.createElement('div');
                user.className = 'result-user';
                user.textContent = result.share_user || '未知';
                titleRow.appendChild(user);
                
                resultItem.appendChild(titleRow);
                
                // 文件信息预览
                if (result.files) {
                    const files = document.createElement('div');
                    files.className = 'result-files';
                    
                    // 分割文件信息并限制显示3行
                    const fileLines = result.files.split('\n').slice(0, 3);
                    fileLines.forEach(line => {
                        files.innerHTML += `<div class="file-line">${line}</div>`;
                    });
                    
                    resultItem.appendChild(files);
                }
                
                // 更新时间
                const updateTime = document.createElement('div');
                updateTime.className = 'result-time';
                updateTime.textContent = `更新时间: ${result.update_time || '未知'}`;
                resultItem.appendChild(updateTime);
                
                // 网盘链接
                if (result.link) {
                    const linkContainer = document.createElement('div');
                    linkContainer.className = 'result-link-container';
                    
                    const link = document.createElement('a');
                    link.className = 'result-link';
                    link.textContent = result.link;
                    link.href = 'javascript:void(0)';
                    link.addEventListener('click', function() {
                        copyToClipboard(result.link);
                    });
                    
                    linkContainer.appendChild(link);
                    resultItem.appendChild(linkContainer);
                }
                
                searchResults.appendChild(resultItem);
            });
            
            // 计算总页数并渲染分页
            totalPages = Math.ceil(total / pageSize);
            renderPagination();
        }
        
        // 渲染分页控件
        function renderPagination() {
            if (totalPages <= 1) {
                pagination.style.display = 'none';
                return;
            }
            
            pagination.style.display = 'flex';
            pagination.innerHTML = '';
            
            // 添加上一页按钮
            const prevButton = document.createElement('div');
            prevButton.className = 'pagination-button prev';
            prevButton.textContent = '上一页';
            prevButton.disabled = currentPage === 1;
            if (currentPage > 1) {
                prevButton.addEventListener('click', () => goToPage(currentPage - 1));
            } else {
                prevButton.classList.add('disabled');
            }
            pagination.appendChild(prevButton);
            
            // 确定要显示的页码范围
            let startPage = Math.max(currentPage - 2, 1);
            let endPage = Math.min(startPage + 4, totalPages);
            
            if (endPage - startPage < 4) {
                startPage = Math.max(endPage - 4, 1);
            }
            
            // 添加第一页按钮
            if (startPage > 1) {
                const firstButton = document.createElement('div');
                firstButton.className = 'pagination-button';
                firstButton.textContent = '1';
                firstButton.addEventListener('click', () => goToPage(1));
                pagination.appendChild(firstButton);
                
                // 添加省略号
                if (startPage > 2) {
                    const ellipsis = document.createElement('div');
                    ellipsis.className = 'pagination-ellipsis';
                    ellipsis.textContent = '...';
                    pagination.appendChild(ellipsis);
                }
            }
            
            // 添加页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const pageButton = document.createElement('div');
                pageButton.className = 'pagination-button';
                if (i === currentPage) {
                    pageButton.classList.add('active');
                }
                pageButton.textContent = i;
                pageButton.addEventListener('click', () => goToPage(i));
                pagination.appendChild(pageButton);
            }
            
            // 添加最后页按钮
            if (endPage < totalPages) {
                // 添加省略号
                if (endPage < totalPages - 1) {
                    const ellipsis = document.createElement('div');
                    ellipsis.className = 'pagination-ellipsis';
                    ellipsis.textContent = '...';
                    pagination.appendChild(ellipsis);
                }
                
                const lastButton = document.createElement('div');
                lastButton.className = 'pagination-button';
                lastButton.textContent = totalPages;
                lastButton.addEventListener('click', () => goToPage(totalPages));
                pagination.appendChild(lastButton);
            }
            
            // 添加下一页按钮
            const nextButton = document.createElement('div');
            nextButton.className = 'pagination-button next';
            nextButton.textContent = '下一页';
            nextButton.disabled = currentPage === totalPages;
            if (currentPage < totalPages) {
                nextButton.addEventListener('click', () => goToPage(currentPage + 1));
            } else {
                nextButton.classList.add('disabled');
            }
            pagination.appendChild(nextButton);
        }
        
        // 跳转到指定页码
        function goToPage(page) {
            if (page !== currentPage && page >= 1 && page <= totalPages) {
                currentPage = page;
                searchWithFilters();
                // 滚动到顶部
                window.scrollTo(0, 0);
            }
        }
        
        // 复制到剪贴板
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text)
                .then(() => {
                    showCopySuccess();
                })
                .catch(err => {
                    // 回退方案
                    const textarea = document.createElement('textarea');
                    textarea.value = text;
                    textarea.style.position = 'fixed';
                    document.body.appendChild(textarea);
                    textarea.select();
                    try {
                        document.execCommand('copy');
                        showCopySuccess();
                    } catch (e) {
                        showError('复制失败，请手动复制');
                    }
                    document.body.removeChild(textarea);
                });
        }
        
        // 显示复制成功提示
        function showCopySuccess() {
            const toast = document.createElement('div');
            toast.className = 'copy-toast';
            toast.textContent = '链接已复制到剪贴板';
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.classList.add('show');
                setTimeout(() => {
                    toast.classList.remove('show');
                    setTimeout(() => {
                        document.body.removeChild(toast);
                    }, 300);
                }, 2000);
            }, 10);
        }
        
        // 显示加载状态
        function showLoading() {
            loadingContainer.style.display = 'flex';
            searchResults.style.display = 'none';
            pagination.style.display = 'none';
            errorMessage.style.display = 'none';
        }
        
        // 隐藏加载状态
        function hideLoading() {
            loadingContainer.style.display = 'none';
        }
        
        // 显示错误信息
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            searchResults.style.display = 'none';
            pagination.style.display = 'none';
        }
    });
</script>
{% endblock %} 